//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package cn.ekuma.epos.productsfinishing;

import com.openbravo.bean.shard.CodeType;
import com.openbravo.bean.TaxCategory;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


import com.openbravo.format.Formats;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.data.loader.query.QBFParameter;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.pos.base.AppLocal;
import e.odbo.data.dao.ChildEditorRecord;
import e.odbo.data.dao.I_ParentNode;
import cn.ekuma.data.ui.swing.AbstractParentDAOJEditor;
import cn.ekuma.data.ui.swing.JChildDAOEditorPanel;
import cn.ekuma.data.ui.swing.JEditorWarpDialog;
import cn.ekuma.data.ui.swing.ParentNodeChangeListener;
import cn.ekuma.epos.businesslogic.ProductUtil;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.db.table.I_Product;
import cn.ekuma.epos.panel.JFinderDialog;
import cn.ekuma.epos.swing.panel.JHashTableEditor;

import com.openbravo.bean.AttributeSet;
import com.openbravo.bean.Product;
import com.openbravo.bean.ProductBom;
import com.openbravo.bean.ProductCategory;
import com.openbravo.bean.ProductReserve;
import com.openbravo.pos.bean.ProductExt;
import com.openbravo.bean.Tax;
import com.openbravo.pos.inventory.AuxiliarEditor;
import com.openbravo.pos.inventory.model.BomProductTableModel;
import com.openbravo.pos.inventory.model.ProductAttributeValuePriceTableModel;
import com.openbravo.pos.inventory.model.ProductAuxiliarTableModel;
import com.openbravo.pos.inventory.model.ProductCodeTableModel;
import com.openbravo.pos.inventory.model.ProductCustomerCategoryPriceModel;
import com.openbravo.pos.inventory.model.ProductPriceTableModel;
import com.openbravo.pos.inventory.model.ProductScoreTableModel;
import com.openbravo.pos.inventory.model.ProductStockLevelTableModel;
import com.openbravo.pos.panels.JCategoryTreeDialog;
import com.openbravo.pos.quickfinder.JProductFinder;
import com.openbravo.pos.sales.TaxesLogic;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import org.krysalis.barcode4j.impl.code128.CheckDigit;

/**
 *
 * @author adrianromero
 */
public class ProductsEditor extends AbstractParentDAOJEditor<ProductExt,String> implements ChildEditorRecord<ProductExt>,ParentNodeChangeListener<String>{

	I_DataLogicERP dlSales;
    private ComboBoxValModel m_CategoryModel;

    private ComboBoxValModel taxcatmodel;  

    private ComboBoxValModel attmodel;
    
    private TaxesLogic taxeslogic;
    
    private ComboBoxValModel m_CodetypeModel;
    
    private Object pricesell;
    private boolean priceselllock = false;
    
    private boolean reportlock = false;

    static SimpleDateFormat sdf=new SimpleDateFormat("SSSSddmm");
    private List catList;

    private ProductCustomerCategoryPriceModel customerCategoryPriceModel;


    JChildDAOEditorPanel bomProductPanel;
    JChildDAOEditorPanel productCustomerPriceEditor;
    JChildDAOEditorPanel productCodeEditor;
    JChildDAOEditorPanel productAuxiliarEditor;
    JChildDAOEditorPanel productStockLevelEditor;
    JChildDAOEditorPanel productScoreEditor;
    JChildDAOEditorPanel productAttributeValuePriceEditor;
    
	private JCheckBox jm_bManufacturering;
	private JTextField jm_iDurability;
	private JChildDAOEditorPanel productPriceEditor;
	private JCheckBox ckbBomStore;
    
    /** Creates new form JEditProduct */
    public ProductsEditor(I_DataLogicERP dlSales, DirtyManager dirty) {
        super(dirty);
        initComponents();

        this.dlSales=dlSales;
        
        m_CategoryModel = new ComboBoxValModel();
        
        // The taxes model
        taxcatmodel = new ComboBoxValModel();

        // The attributes model
        attmodel = new ComboBoxValModel();
        
        m_CodetypeModel = new ComboBoxValModel();
        m_CodetypeModel.add(null);
        m_CodetypeModel.add(CodeType.EAN13);
        m_CodetypeModel.add(CodeType.CODE128);
        m_jCodetype.setModel(m_CodetypeModel);
        
        JButton btnP = new JButton("P");
        btnP.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		showSimilarProduct();
        	}
        });
        btnP.setBounds(300, 9, 32, 23);
        jPanel1.add(btnP);
        

        m_jCodetype.setVisible(false);
               
        m_jRef.getDocument().addDocumentListener(dirty);
        m_jCode.getDocument().addDocumentListener(dirty);
        m_jName.getDocument().addDocumentListener(dirty);
        m_jComment.addActionListener(dirty);
        m_jScale.addActionListener(dirty);
        m_jCategory.addActionListener(dirty);
        m_jTax.addActionListener(dirty);
        m_jAtt.addActionListener(dirty);
        m_jPriceBuy.getDocument().addDocumentListener(dirty);
        m_jPriceSell.getDocument().addDocumentListener(dirty);
        m_jImage.addPropertyChangeListener("image", dirty);
        m_jstockcost.getDocument().addDocumentListener(dirty);
        m_jstockvolume.getDocument().addDocumentListener(dirty);
        m_jInCatalog.addActionListener(dirty);
        m_jCatalogOrder.getDocument().addDocumentListener(dirty);
        m_jCustomerPrice.getDocument().addDocumentListener(dirty);

        jm_origin.getDocument().addDocumentListener(dirty);
        jm_unit.getDocument().addDocumentListener(dirty);
        jm_quantity.getDocument().addDocumentListener(dirty);

        jm_sManufacturer.getDocument().addDocumentListener(dirty);
        jm_similarCode.getDocument().addDocumentListener(dirty);
        jMnemonic.getDocument().addDocumentListener(dirty);
        
        jm_bManufacturering.addActionListener(dirty);
        ckbBomStore.addActionListener(dirty);

        m_jWholesalePrice.getDocument().addDocumentListener(dirty);
        m_jWholesalePrice.getDocument().addDocumentListener(new WholesalePriceManager());
        m_jWholesalePriceMargin.getDocument().addDocumentListener(new WholesalePriceMarginManager());
        
        jSpecification.getDocument().addDocumentListener(dirty);
        
        FieldsManager fm = new FieldsManager();
        m_jPriceBuy.getDocument().addDocumentListener(fm);
        m_jPriceSell.getDocument().addDocumentListener(new PriceSellManager());
        m_jTax.addActionListener(fm);
        
        m_jPriceSellTax.getDocument().addDocumentListener(new PriceTaxManager());
        m_jmargin.getDocument().addDocumentListener(new MarginManager());

        m_jCustomerPrice.getDocument().addDocumentListener(new CustomerPriceSellManager());
        m_jCustomerPriceMargin.getDocument().addDocumentListener(new CustomerMarginManager());

        bomProductPanel=new  JChildDAOEditorPanel(dlSales,new BomProductTableModel(),new ProductBomEditor(dlSales,new DirtyManager()));
        jTabbedPane1.add(bomProductPanel.getTabName(), bomProductPanel);
        addObjectChangeListener(bomProductPanel);

        productCustomerPriceEditor=new  JChildDAOEditorPanel(dlSales,new ProductCustomerCategoryPriceModel(),new ProductCustomerPriceEditor(dlSales,new DirtyManager()));
        jTabbedPane1.add(productCustomerPriceEditor.getTabName(), productCustomerPriceEditor);
        addObjectChangeListener(productCustomerPriceEditor);
        
        productCodeEditor=new  JChildDAOEditorPanel(dlSales,new ProductCodeTableModel(),new ProductCodeEditor(new DirtyManager()));
        jTabbedPane1.add(productCodeEditor.getTabName(), productCodeEditor);
        addObjectChangeListener(productCodeEditor);
        
        productAuxiliarEditor=new  JChildDAOEditorPanel(dlSales,new ProductAuxiliarTableModel(),new AuxiliarEditor(dlSales,new DirtyManager()));
        jTabbedPane1.add(productAuxiliarEditor.getTabName(), productAuxiliarEditor);
        addObjectChangeListener(productAuxiliarEditor);
        
        productStockLevelEditor=new JChildDAOEditorPanel(dlSales,new ProductStockLevelTableModel(),new ProductStockLevelEditor(dlSales,new DirtyManager()));
        jTabbedPane1.add(productStockLevelEditor.getTabName(), productStockLevelEditor);
        addObjectChangeListener(productStockLevelEditor);
        
        productPriceEditor=new JChildDAOEditorPanel(dlSales,new ProductPriceTableModel(),new ProductPriceEditor(new DirtyManager()));
        jTabbedPane1.add(productPriceEditor.getTabName(), productPriceEditor);
        addObjectChangeListener(productPriceEditor);
        
        productScoreEditor=new JChildDAOEditorPanel(dlSales,new ProductScoreTableModel(),new ProductScoreEditor(new DirtyManager()));
        jTabbedPane1.add(productScoreEditor.getTabName(), productScoreEditor);
        addObjectChangeListener(productScoreEditor);
        
        productAttributeValuePriceEditor=new JChildDAOEditorPanel(dlSales,new ProductAttributeValuePriceTableModel(),new ProductAttributeValuePriceEditor(new DirtyManager(),dlSales));
        jTabbedPane1.add(productAttributeValuePriceEditor.getTabName(), productAttributeValuePriceEditor);
        addObjectChangeListener(productAttributeValuePriceEditor);
    }
    
    protected void showSimilarProduct() {
		String code=m_jCode.getText();
		//高级功能，用于确定参照价
		if(code.length()==13)
			code=code.substring(0, 10);
         QBFParameter  para=new QBFParameter(I_Product.CODE);
         para.like(code);
         JFinderDialog finderDialog=JFinderDialog.getInstance(this, new JProductFinder(dlSales));
         finderDialog.query(para);
	}

	public void activate() throws BasicException {
        
        // Load the taxes logic
        taxeslogic = new TaxesLogic(dlSales.list(Tax.class));
        catList=dlSales.list(ProductCategory.class);
        m_CategoryModel = new ComboBoxValModel(catList);
        m_jCategory.setModel(m_CategoryModel);

        taxcatmodel = new ComboBoxValModel(dlSales.list(TaxCategory.class));
        m_jTax.setModel(taxcatmodel);

        attmodel = new ComboBoxValModel(dlSales.list(AttributeSet.class));
        attmodel.add(0, null);
        m_jAtt.setModel(attmodel);

        bomProductPanel.activate();
        productCustomerPriceEditor.activate();
        if(state==this.STATE_Edit){
        	updateUI(true, state);
        }
    }
    
    public void refresh() {
    } 
    
    public Component getComponent() {
        return this;
    }
    
    private void productReserve(){
    	if(m_jCode.getText()==null||m_jCode.getText().isEmpty())
    		return;
    	int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.productReserve"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res == JOptionPane.YES_OPTION){
        String code1=m_jCode.getText();
       	 try {
				ProductReserve productReserve=dlSales.getProductReserveByCode(code1);
				if(productReserve!=null){
					obj.copyFor(productReserve);
					updateUI(true, state);
				}
			} catch (BasicException e) {
			} 
        }
    }
    
    
    private void calculateCustomerPriceMargin(){
        if (!reportlock) {
            reportlock = true;
            Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
            Double dPriceSell = (Double)readCurrency(m_jCustomerPrice.getText());

            if (dPriceBuy == null || dPriceSell == null) {
                m_jCustomerPriceMargin.setText(null);
            } else {
                m_jCustomerPriceMargin.setText(Formats.PERCENT.formatValue(new Double(dPriceSell.doubleValue() / dPriceBuy.doubleValue() - 1.0)));
            }
            reportlock = false;
        }
    }

     private void calculateCustomerPriceSellfromMargin() {
         if (!reportlock) {
            reportlock = true;
            Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
            Double dMargin = readPercent(m_jCustomerPriceMargin.getText());

            if (dMargin == null || dPriceBuy == null) {
                m_jCustomerPrice.setText(null);
            } else {
                m_jCustomerPrice.setText(Formats.CURRENCY.formatValue(new Double(dPriceBuy.doubleValue() * (1.0 + dMargin.doubleValue()))));
            }
           reportlock = false;
        }
    }
    
     private void calculateWholesalePriceMargin(){
         if (!reportlock) {
             reportlock = true;
             Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
             Double dPriceSell = (Double)readCurrency(m_jWholesalePrice.getText());

             if (dPriceBuy == null || dPriceSell == null) {
                 m_jWholesalePriceMargin.setText(null);
             } else {
                 m_jWholesalePriceMargin.setText(Formats.PERCENT.formatValue(new Double(dPriceSell.doubleValue() / dPriceBuy.doubleValue() - 1.0)));
             }
             reportlock = false;
         }
     }

      private void calculateWholesalePricefromMargin() {
          if (!reportlock) {
             reportlock = true;
             Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
             Double dMargin = readPercent(m_jWholesalePriceMargin.getText());

             if (dMargin == null || dPriceBuy == null) {
                 m_jWholesalePrice.setText(null);
             } else {
                 m_jWholesalePrice.setText(Formats.CURRENCY.formatValue(new Double(dPriceBuy.doubleValue() * (1.0 + dMargin.doubleValue()))));
             }
            reportlock = false;
         }
     } 
     
     
    private void calculateMargin() {
        
        if (!reportlock) {
            reportlock = true;
            
            Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
            Double dPriceSell = (Double) pricesell;

            if (dPriceBuy == null || dPriceSell == null) {
                m_jmargin.setText(null);
            } else {
                m_jmargin.setText(Formats.PERCENT.formatValue(new Double(dPriceSell.doubleValue() / dPriceBuy.doubleValue() - 1.0)));
            }    
            reportlock = false;
        }
    }
    
    private void calculatePriceSellTax() {
        
        if (!reportlock) {
            reportlock = true;
            
            Double dPriceSell = (Double) pricesell;
            
            if (dPriceSell == null) {
                m_jPriceSellTax.setText(null);
            } else {               
                double dTaxRate = taxeslogic.getTaxRate((TaxCategory) taxcatmodel.getSelectedItem());
                m_jPriceSellTax.setText(Formats.CURRENCY.formatValue(new Double(dPriceSell.doubleValue() * (1.0 + dTaxRate))));
            }            
            reportlock = false;
        }
    }
    
    private void calculatePriceSellfromMargin() {
        
        if (!reportlock) {
            reportlock = true;
            
            Double dPriceBuy = readCurrency(m_jPriceBuy.getText());
            Double dMargin = readPercent(m_jmargin.getText());  
            
            if (dMargin == null || dPriceBuy == null) {
                setPriceSell(null);
            } else {
                setPriceSell(new Double(dPriceBuy.doubleValue() * (1.0 + dMargin.doubleValue())));
            }                        
            
            reportlock = false;
        }
      
    }
    
    private void calculatePriceSellfromPST() {
        
        if (!reportlock) {
            reportlock = true;
                    
            Double dPriceSellTax = readCurrency(m_jPriceSellTax.getText());  

            if (dPriceSellTax == null) {
                setPriceSell(null);
            } else {
                double dTaxRate = taxeslogic.getTaxRate((TaxCategory) taxcatmodel.getSelectedItem());
                setPriceSell(new Double(dPriceSellTax.doubleValue() / (1.0 + dTaxRate)));
            }   
                        
            reportlock = false;
        }    
    }
    
    private void setPriceSell(Object value) {
        if (!priceselllock) {
            priceselllock = true;
            pricesell = value;
            m_jPriceSell.setText(Formats.CURRENCY.formatValue(pricesell));  
            priceselllock = false;
        }
    }

    @Override
    public ProductExt createNew(Properties prop) {
        ProductExt newObj=new ProductExt(); 
        String code=sdf.format(new Date());
        int i=0;
        while(true){
          code=code.substring(1);
          code+=CheckDigit.calcCheckdigit(code,0,7,CheckDigit.CD31);
           try {
			if(!dlSales.isExistByField(Product.class,I_Product.REFERENCE,code))
			       break;
		} catch (BasicException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
           if(i>10)
        	   break;
           code=sdf.format(new Date());
           i++;
        }
        if(prop!=null&&prop.getProperty(I_Product.REFERENCE)!=null){
        	 String code1=prop.getProperty(I_Product.REFERENCE);
        	 newObj.setCode(code1);
        	 try {
				ProductReserve productReserve=dlSales.getProductReserveByCode(code1);
				if(productReserve!=null){
					newObj.copyFor(productReserve);
				}
			} catch (BasicException e) {
				e.printStackTrace();
			} 
        }else
             newObj.setCode(code);
        newObj.setReference(code);
        newObj.setCurDate(new Date());
        if(parentNode!=null)
        	newObj.setCategoryID(parentNode.getParentKey().getKey());
        return newObj;
    }

    @Override
    public void updateUI(boolean editAble, int state) {
        reportlock = true;
        m_jTitle.setText(Formats.STRING.formatValue(obj.getReference()) + " - " + Formats.STRING.formatValue(obj.getName()));
        m_jRef.setText(obj.getReference());
        m_jCode.setText(Formats.STRING.formatValue(obj.getCode()));
        m_jName.setText(Formats.STRING.formatValue(obj.getName()));
        m_jComment.setSelected(obj.isCom());
        m_jScale.setSelected(obj.isScale());
        attmodel.setSelectedKey(obj.getAttributeSetID());
        m_jImage.setImage(ImageUtils.readImage(obj.getImage()));
        m_jstockcost.setText(Formats.CURRENCY.formatValue(obj.getStockCost()));
        m_jstockvolume.setText(Formats.DOUBLE.formatValue(obj.getStockVolume()));
        m_jInCatalog.setSelected(obj.isCatalog());
        m_jCatalogOrder.setText(Formats.INT.formatValue(obj.getCatorder()));
        hashTableEditor.setHashMap(obj.getProperties(), true);
        jm_origin.setText(Formats.STRING.formatValue(obj.getM_origin()));
        jm_quantity.setText(Formats.DOUBLE.formatValue(obj.getM_quantity()));
        jm_unit.setText(Formats.STRING.formatValue(obj.getM_unit()));
        jm_sManufacturer.setText(Formats.STRING.formatValue(obj.getM_sManufacturer()));
        jm_similarCode.setText(Formats.STRING.formatValue(obj.getM_sSimilarCode()));
        jm_iDurability.setText(Formats.INT.formatValue(obj.getM_iDurability()));
        jMnemonic.setText(Formats.STRING.formatValue(obj.getMnemonic()));
        jm_bManufacturering.setSelected(obj.isM_bManufacturing());
        reportlock = false;
        if(state!=STATE_Insert){
        	m_CategoryModel.setSelectedKey(obj.getCategoryID());
            taxcatmodel.setSelectedKey(obj.getTaxCategoryID());
        	m_jPriceBuy.setText(Formats.CURRENCY.formatValue(obj.getPriceBuy()));
            setPriceSell(obj.getPriceSell());
            m_jCustomerPrice.setText(Formats.CURRENCY.formatValue(obj.getM_dCustomerPrice()));
            m_jWholesalePrice.setText(Formats.CURRENCY.formatValue(obj.getM_dWholesalePrice()));
            calculateMargin();
            calculatePriceSellTax();
            calculateCustomerPriceMargin();
            calculateWholesalePriceMargin();
        }else{
        	m_jPriceBuy.setText(null);
            m_jCustomerPrice.setText(null);
            m_jPriceSell.setText(null);
            m_jWholesalePrice.setText(null);
            if(obj.getCategoryID()!=null)
            	m_CategoryModel.setSelectedKey(obj.getCategoryID());
        }  
        jCurDate.setText(Formats.TIMESTAMP.formatValue(obj.getCurDate()));
        jWeight.setText(Formats.DOUBLE.formatValue(obj.getWeight()));
        ckbBomStore.setSelected(obj.isBomStore());
        jSpecification.setText(obj.getSpecification());
        
        // Los habilitados
        m_jRef.setEnabled(editAble);
        m_jCode.setEnabled(editAble);
        m_jName.setEnabled(editAble);
        m_jComment.setEnabled(editAble);
        m_jScale.setEnabled(editAble);
        m_jCategory.setEnabled(editAble);
        m_jTax.setEnabled(editAble);
        m_jAtt.setEnabled(editAble);
        m_jPriceBuy.setEnabled(editAble);
        m_jPriceSell.setEnabled(editAble);
        m_jPriceSellTax.setEnabled(editAble);
        m_jmargin.setEnabled(editAble);
        m_jImage.setEnabled(editAble);
        m_jstockcost.setEnabled(editAble);
        m_jstockvolume.setEnabled(editAble);
        m_jInCatalog.setEnabled(editAble);
        m_jCatalogOrder.setEnabled(m_jInCatalog.isSelected());
        hashTableEditor.setEnabled(editAble);
        m_jCustomerPrice.setEnabled(editAble);
        m_jCustomerPriceMargin.setEnabled(editAble);

        m_jWholesalePrice.setEnabled(editAble);
        m_jWholesalePriceMargin.setEnabled(editAble);
        
        jm_origin.setEditable(editAble);
        jm_unit.setEditable(editAble);
        jm_quantity.setEditable(editAble);

        jm_sManufacturer.setEditable(editAble);
        jm_similarCode.setEditable(editAble);
        jm_iDurability.setEditable(editAble);
        jMnemonic.setEditable(editAble);

        jSearchCategory.setEnabled(editAble);
        JProductReserveBtn.setEnabled(editAble);
        jm_bManufacturering.setEnabled(editAble);
        jWeight.setEditable(editAble);
        ckbBomStore.setEnabled(editAble);
        jSpecification.setEditable(editAble);
        
        m_jButtonDaBao.setEnabled(state==STATE_Edit);
    }

    @Override
    public void rebuild(ProductExt product)throws BasicException  {
        product.setReference(m_jRef.getText());
        product.setCode(m_jCode.getText());
        product.setName(m_jName.getText());
        product.setCom(m_jComment.isSelected());
        product.setScale(m_jScale.isSelected());
        product.setPriceBuy((Double)Formats.CURRENCY.parseValue(m_jPriceBuy.getText()));
        product.setPriceSell((Double)Formats.CURRENCY.parseValue(m_jPriceSell.getText()));
        product.setCategoryID((String) m_CategoryModel.getSelectedKey());
        product.setTaxCategoryID((String) taxcatmodel.getSelectedKey());
        product.setAttributeSetID((String) attmodel.getSelectedKey());
        product.setImage(ImageUtils.writeImage(m_jImage.getImage()));
        product.setM_dCustomerPrice((Double)Formats.CURRENCY.parseValue(m_jCustomerPrice.getText(),0.0));
        product.setM_dWholesalePrice((Double)Formats.CURRENCY.parseValue(m_jWholesalePrice.getText(),0.0));
        product.setM_origin(jm_origin.getText());
        product.setM_quantity((Double)Formats.DOUBLE.parseValue(jm_quantity.getText()));
        product.setM_unit((String) jm_unit.getText());
        product.setM_sManufacturer(jm_sManufacturer.getText());
        product.setM_sSimilarCode(jm_similarCode.getText());
        product.setM_iDurability((Integer)Formats.INT.parseValue(jm_iDurability.getText()));
        product.setMnemonic(jMnemonic.getText()==null?null:jMnemonic.getText().toUpperCase());
        product.setCatalog(m_jInCatalog.isSelected());
        product.setCatorder(m_jInCatalog.isSelected()==false?0:(Integer)Formats.INT.parseValue(m_jCatalogOrder.getText()));
        product.setStockCost((Double)Formats.CURRENCY.parseValue(m_jstockcost.getText()));
        product.setStockVolume((Double)Formats.DOUBLE.parseValue(m_jstockvolume.getText()));
        product.setM_bManufacturing(jm_bManufacturering.isSelected());
        product.setWeight((Double)Formats.DOUBLE.parseValue(jWeight.getText()));
        product.setBomStore(ckbBomStore.isSelected());
        product.setSpecification(jSpecification.getText());
        product.setAttributes(hashTableEditor.getHashMap());
    }

    @Override
    public Class getEditClass() {
        return ProductExt.class;
    }
    
    private class PriceSellManager implements DocumentListener {
        public void changedUpdate(DocumentEvent e) {
            if (!priceselllock) {
                priceselllock = true;
                pricesell = readCurrency(m_jPriceSell.getText());
                priceselllock = false;
            }
            calculateMargin();
            calculatePriceSellTax();
        }
        public void insertUpdate(DocumentEvent e) {
            if (!priceselllock) {
                priceselllock = true;
                pricesell = readCurrency(m_jPriceSell.getText());
                priceselllock = false;
            }
            calculateMargin();
            calculatePriceSellTax();
        }    
        public void removeUpdate(DocumentEvent e) {
            if (!priceselllock) {
                priceselllock = true;
                pricesell = readCurrency(m_jPriceSell.getText());
                priceselllock = false;
            }
            calculateMargin();
            calculatePriceSellTax();
        }  
    }


    private class FieldsManager implements DocumentListener, ActionListener {
        public void changedUpdate(DocumentEvent e) {
            calculateMargin();
            calculatePriceSellTax();
            calculateCustomerPriceMargin();
        }
        public void insertUpdate(DocumentEvent e) {
            calculateMargin();
            calculatePriceSellTax();
            calculateCustomerPriceMargin();
        }    
        public void removeUpdate(DocumentEvent e) {
            calculateMargin();
            calculatePriceSellTax();
            calculateCustomerPriceMargin();
        }         
        public void actionPerformed(ActionEvent e) {
            calculateMargin();
            calculatePriceSellTax();
            calculateCustomerPriceMargin();
        }
    }

    private class PriceTaxManager implements DocumentListener {
        public void changedUpdate(DocumentEvent e) {
            calculatePriceSellfromPST();
            calculateMargin();
        }
        public void insertUpdate(DocumentEvent e) {
            calculatePriceSellfromPST();
            calculateMargin();
        }    
        public void removeUpdate(DocumentEvent e) {
            calculatePriceSellfromPST();
            calculateMargin();
        }         
    }
    
    private class MarginManager implements DocumentListener  {
        public void changedUpdate(DocumentEvent e) {
            calculatePriceSellfromMargin();
            calculatePriceSellTax();
        }
        public void insertUpdate(DocumentEvent e) {
            calculatePriceSellfromMargin();
            calculatePriceSellTax();
        }    
        public void removeUpdate(DocumentEvent e) {
            calculatePriceSellfromMargin();
            calculatePriceSellTax();
        }         
    }

     private class CustomerMarginManager implements DocumentListener  {
        public void changedUpdate(DocumentEvent e) {
           calculateCustomerPriceSellfromMargin();
        }
        public void insertUpdate(DocumentEvent e) {
           calculateCustomerPriceSellfromMargin();
        }
        public void removeUpdate(DocumentEvent e) {
            calculateCustomerPriceSellfromMargin();
        }
    }

     private class CustomerPriceSellManager implements DocumentListener {
        public void changedUpdate(DocumentEvent e) {
            calculateCustomerPriceMargin();
        }
        public void insertUpdate(DocumentEvent e) {
            calculateCustomerPriceMargin();
        }
        public void removeUpdate(DocumentEvent e) {
            calculateCustomerPriceMargin();
        }
    }
     
     private class WholesalePriceMarginManager implements DocumentListener  {
         public void changedUpdate(DocumentEvent e) {
            calculateWholesalePricefromMargin();
         }
         public void insertUpdate(DocumentEvent e) {
            calculateWholesalePricefromMargin();
         }
         public void removeUpdate(DocumentEvent e) {
             calculateWholesalePricefromMargin();
         }
     }

      private class WholesalePriceManager implements DocumentListener {
         public void changedUpdate(DocumentEvent e) {
             calculateWholesalePriceMargin();
         }
         public void insertUpdate(DocumentEvent e) {
             calculateWholesalePriceMargin();
         }
         public void removeUpdate(DocumentEvent e) {
             calculateWholesalePriceMargin();
         }
     } 
     

    private final static Double readCurrency(String sValue) {
        try {
            return (Double) Formats.CURRENCY.parseValue(sValue);
        } catch (BasicException e) {
            return 0.0;
        }
    }
        
    private final static Double readPercent(String sValue) {
        try {
            return (Double) Formats.PERCENT.parseValue(sValue);
        } catch (BasicException e) {
            return null;
        }
    }
    JHashTableEditor hashTableEditor;
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        m_jRef = new javax.swing.JTextField();
        m_jName = new javax.swing.JTextField();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        m_jCode = new javax.swing.JTextField();
        m_jImage = new com.openbravo.data.gui.JImageEditor();
        jLabel3 = new javax.swing.JLabel();
        m_jPriceBuy = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        m_jPriceSell = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        m_jCategory = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        m_jTax = new javax.swing.JComboBox();
        m_jmargin = new javax.swing.JTextField();
        m_jPriceSellTax = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        m_jCodetype = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        m_jAtt = new javax.swing.JComboBox();
        jCustomerPriceLabel = new javax.swing.JLabel();
        m_jCustomerPrice = new javax.swing.JTextField();
        m_jCustomerPriceMargin = new javax.swing.JTextField();
        jSearchCategory = new javax.swing.JButton();
        jm_quantity = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jm_unit = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jm_origin = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jm_similarCode = new javax.swing.JTextField();
        jLabel21 = new javax.swing.JLabel();
        jm_sManufacturer = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        m_jstockcost = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        m_jstockvolume = new javax.swing.JTextField();
        m_jScale = new javax.swing.JCheckBox();
        m_jComment = new javax.swing.JCheckBox();
        jLabel18 = new javax.swing.JLabel();
        m_jCatalogOrder = new javax.swing.JTextField();
        m_jInCatalog = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        m_jTitle = new javax.swing.JLabel();
        jMnemonic = new javax.swing.JTextField();
        hashTableEditor=new JHashTableEditor();

        setLayout(null);

        jLabel1.setText(AppLocal.getIntString("label.prodref")); // NOI18N
        add(jLabel1);
        jLabel1.setBounds(10, 40, 70, 15);

        jLabel2.setText(AppLocal.getIntString("label.prodname")); // NOI18N
        add(jLabel2);
        jLabel2.setBounds(160, 40, 70, 15);
        add(m_jRef);
        m_jRef.setBounds(80, 37, 70, 21);
        add(m_jName);
        m_jName.setBounds(230, 37, 203, 21);

        jPanel1.setLayout(null);

        jLabel6.setText(AppLocal.getIntString("label.prodbarcode")); // NOI18N
        jPanel1.add(jLabel6);
        jLabel6.setBounds(10, 10, 150, 15);
        jPanel1.add(m_jCode);
        m_jCode.setBounds(160, 10, 110, 21);
        jPanel1.add(m_jImage);
        m_jImage.setBounds(340, 10, 200, 200);

        JProductReserveBtn = new JButton(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/search.png")));
        JProductReserveBtn.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		productReserve();
        	}
        });
        JProductReserveBtn.setRequestFocusEnabled(false);
        JProductReserveBtn.setPreferredSize(new Dimension(35, 25));
        JProductReserveBtn.setFocusable(false);
        JProductReserveBtn.setBounds(270, 10, 30, 20);
        jPanel1.add(JProductReserveBtn);
        
        jLabel3.setText(AppLocal.getIntString("label.prodpricebuy")); // NOI18N
        jPanel1.add(jLabel3);
        jLabel3.setBounds(10, 40, 150, 15);

        m_jPriceBuy.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        m_jPriceBuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jPriceBuyActionPerformed(evt);
            }
        });
        jPanel1.add(m_jPriceBuy);
        m_jPriceBuy.setBounds(160, 40, 80, 21);

        jLabel4.setText(AppLocal.getIntString("label.prodpricesell")); // NOI18N
        jPanel1.add(jLabel4);
        jLabel4.setBounds(10, 70, 150, 15);

        m_jPriceSell.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(m_jPriceSell);
        m_jPriceSell.setBounds(160, 70, 80, 21);

        jLabel5.setText(AppLocal.getIntString("label.prodcategory")); // NOI18N
        jPanel1.add(jLabel5);
        jLabel5.setBounds(10, 220, 150, 15);
        jPanel1.add(m_jCategory);
        m_jCategory.setBounds(160, 220, 140, 20);

        jLabel7.setText(AppLocal.getIntString("label.taxcategory")); // NOI18N
        jPanel1.add(jLabel7);
        jLabel7.setBounds(10, 190, 150, 15);
        jPanel1.add(m_jTax);
        m_jTax.setBounds(160, 190, 170, 20);

        m_jmargin.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(m_jmargin);
        m_jmargin.setBounds(250, 70, 80, 21);

        m_jPriceSellTax.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(m_jPriceSellTax);
        m_jPriceSellTax.setBounds(160, 100, 80, 21);

        jLabel16.setText(AppLocal.getIntString("label.prodpriceselltax")); // NOI18N
        jPanel1.add(jLabel16);
        jLabel16.setBounds(10, 100, 150, 15);
        jPanel1.add(m_jCodetype);
        m_jCodetype.setBounds(300, 10, 30, 21);

        jLabel13.setText(AppLocal.getIntString("label.attributes")); // NOI18N
        jPanel1.add(jLabel13);
        jLabel13.setBounds(10, 250, 150, 15);
        jPanel1.add(m_jAtt);
        m_jAtt.setBounds(160, 250, 170, 20);

        jCustomerPriceLabel.setText(AppLocal.getIntString("label.baseCustomerPrice")); // NOI18N
        jPanel1.add(jCustomerPriceLabel);
        jCustomerPriceLabel.setBounds(10, 130, 150, 15);

        m_jCustomerPrice.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(m_jCustomerPrice);
        m_jCustomerPrice.setBounds(160, 130, 80, 21);

        m_jCustomerPriceMargin.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(m_jCustomerPriceMargin);
        m_jCustomerPriceMargin.setBounds(250, 130, 80, 21);

        jSearchCategory.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/search.png"))); // NOI18N
        jSearchCategory.setFocusable(false);
        jSearchCategory.setPreferredSize(new java.awt.Dimension(35, 25));
        jSearchCategory.setRequestFocusEnabled(false);
        jSearchCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jSearchCategoryActionPerformed(evt);
            }
        });
        jPanel1.add(jSearchCategory);
        jSearchCategory.setBounds(300, 220, 30, 20);

        jm_quantity.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel1.add(jm_quantity);
        jm_quantity.setBounds(260, 40, 70, 21);

        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel14.setText("X");
        jPanel1.add(jLabel14);
        jLabel14.setBounds(240, 40, 20, 20);

        jm_unit.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jPanel1.add(jm_unit);
        jm_unit.setBounds(260, 100, 70, 21);

        jLabel15.setText(AppLocal.getIntString("label.product.origin")); // NOI18N
        jPanel1.add(jLabel15);
        jLabel15.setBounds(350, 220, 70, 20);

        jm_origin.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jPanel1.add(jm_origin);
        jm_origin.setBounds(420, 220, 110, 21);

        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel17.setText("/");
        jPanel1.add(jLabel17);
        jLabel17.setBounds(240, 100, 20, 20);

        jLabel19.setText(AppLocal.getIntString("label.product.m_similarCode")); // NOI18N
        jPanel1.add(jLabel19);
        jLabel19.setBounds(350, 250, 70, 20);
        jPanel1.add(jm_similarCode);
        jm_similarCode.setBounds(420, 250, 110, 21);

        jLabel21.setText(AppLocal.getIntString("label.prodcut.m_sManufacturer")); // NOI18N
        jPanel1.add(jLabel21);
        jLabel21.setBounds(10, 280, 150, 20);
        jPanel1.add(jm_sManufacturer);
        jm_sManufacturer.setBounds(160, 280, 170, 21);

        jTabbedPane1.addTab(AppLocal.getIntString("label.prodgeneral"), jPanel1); // NOI18N

        jPanel2.setLayout(null);

        jLabel9.setText(AppLocal.getIntString("label.prodstockcost")); // NOI18N
        jPanel2.add(jLabel9);
        jLabel9.setBounds(10, 20, 150, 15);

        m_jstockcost.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(m_jstockcost);
        m_jstockcost.setBounds(160, 20, 80, 21);

        jLabel10.setText(AppLocal.getIntString("label.prodstockvol")); // NOI18N
        jPanel2.add(jLabel10);
        jLabel10.setBounds(10, 50, 150, 15);

        m_jstockvolume.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel2.add(m_jstockvolume);
        m_jstockvolume.setBounds(160, 50, 80, 21);
        jPanel2.add(m_jScale);
        m_jScale.setBounds(160, 140, 80, 21);
        jPanel2.add(m_jComment);
        m_jComment.setBounds(160, 110, 80, 21);

        jLabel18.setText(AppLocal.getIntString("label.prodorder")); // NOI18N
        jPanel2.add(jLabel18);
        jLabel18.setBounds(250, 80, 60, 15);

        m_jCatalogOrder.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jPanel2.add(m_jCatalogOrder);
        m_jCatalogOrder.setBounds(310, 80, 80, 21);

        m_jInCatalog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jInCatalogActionPerformed(evt);
            }
        });
        jPanel2.add(m_jInCatalog);
        m_jInCatalog.setBounds(160, 80, 50, 21);

        jLabel8.setText(AppLocal.getIntString("label.prodincatalog")); // NOI18N
        jPanel2.add(jLabel8);
        jLabel8.setBounds(10, 80, 150, 15);

        jLabel11.setText(AppLocal.getIntString("label.prodaux")); // NOI18N
        jPanel2.add(jLabel11);
        jLabel11.setBounds(10, 110, 150, 15);

        jLabel12.setText(AppLocal.getIntString("label.prodscale")); // NOI18N
        jPanel2.add(jLabel12);
        jLabel12.setBounds(10, 140, 150, 15);

        jTabbedPane1.addTab(AppLocal.getIntString("label.prodstock"), jPanel2); // NOI18N
        
        jm_bManufacturering = new JCheckBox(AppLocal.getIntString("label.product.manufacturering"));
        jm_bManufacturering.setBounds(266, 16, 103, 23);
        jPanel2.add(jm_bManufacturering);
        
        JLabel lblNewLabel = new JLabel(AppLocal.getIntString("label.createTime"));
        lblNewLabel.setBounds(266, 50, 80, 15);
        jPanel2.add(lblNewLabel);
        
        jCurDate = new JTextField();
        jCurDate.setBounds(360, 47, 167, 21);
        jPanel2.add(jCurDate);
        jCurDate.setColumns(10);
        
        JLabel lblWeight = new JLabel(AppLocal.getIntString("label.product.weight"));
        lblWeight.setBounds(246, 110, 64, 15);
        jPanel2.add(lblWeight);
        
        jWeight = new JTextField();
        jWeight.setBounds(310, 110, 80, 21);
        jPanel2.add(jWeight);
        jWeight.setColumns(10);
        
        ckbBomStore = new JCheckBox(AppLocal.getIntString("label.product.isbomstore"));
        ckbBomStore.setBounds(363, 16, 103, 23);
        jPanel2.add(ckbBomStore);

        jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
        jPanel3.setLayout(new java.awt.BorderLayout());


        jPanel3.add(hashTableEditor, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab(AppLocal.getIntString("label.properties"), jPanel3); // NOI18N

        add(jTabbedPane1);
        jTabbedPane1.setBounds(10, 65, 560, 360);

        m_jTitle.setFont(new java.awt.Font("SansSerif", 3, 18));
        add(m_jTitle);
        m_jTitle.setBounds(10, 0, 320, 30);
        add(jMnemonic);
        jMnemonic.setBounds(499, 37, 51, 21);
        
        JLabel label = new JLabel();
        label.setText(AppLocal.getIntString("label.WholesalePrice"));
        label.setBounds(10, 159, 150, 15);
        jPanel1.add(label);
        
        m_jWholesalePrice = new JTextField();
        m_jWholesalePrice.setHorizontalAlignment(SwingConstants.RIGHT);
        m_jWholesalePrice.setBounds(160, 159, 80, 21);
        jPanel1.add(m_jWholesalePrice);
        
        m_jWholesalePriceMargin = new JTextField();
        m_jWholesalePriceMargin.setHorizontalAlignment(SwingConstants.RIGHT);
        m_jWholesalePriceMargin.setBounds(250, 159, 80, 21);
        jPanel1.add(m_jWholesalePriceMargin);
        
        JLabel label_1 = new JLabel();
        label_1.setText(AppLocal.getIntString("label.product.m_iDurability"));
        label_1.setBounds(350, 279, 70, 20);
        jPanel1.add(label_1);
        
        jm_iDurability = new JTextField();
        jm_iDurability.setHorizontalAlignment(SwingConstants.CENTER);
        jm_iDurability.setBounds(420, 279, 110, 21);
        jPanel1.add(jm_iDurability);
        
        jSpecification = new JTextField();
        jSpecification.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		checkSpecification();
        	}
        });
        jSpecification.setBounds(433, 37, 66, 21);
        add(jSpecification);
        jSpecification.setColumns(10);
        
        setPreferredSize(new Dimension(581, 428));
    }// </editor-fold>//GEN-END:initComponents

    protected void checkSpecification() {
    	String specification=jSpecification.getText();
    	String nameTxt=m_jName.getText();
    	if(nameTxt==null||nameTxt.isEmpty())
    		return;
    	int blo=nameTxt.indexOf("-");
    	if(blo>0&&(specification==null||specification.isEmpty()))
    	  jSpecification.setText(nameTxt.substring(blo+1));
	}

	private void m_jInCatalogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jInCatalogActionPerformed
 
        if (m_jInCatalog.isSelected()) {
            m_jCatalogOrder.setEnabled(true);   
        } else {
            m_jCatalogOrder.setEnabled(false);   
            m_jCatalogOrder.setText(null);   
        }

    }//GEN-LAST:event_m_jInCatalogActionPerformed

    private void jSearchCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSearchCategoryActionPerformed
           JCategoryTreeDialog dailog=JCategoryTreeDialog.newJDialog(this);
           dailog.showDialog(catList,(ProductCategory) m_CategoryModel.getSelectedItem());
           if(dailog.isOK())
               m_CategoryModel.setSelectedItem(dailog.getSelected());
}//GEN-LAST:event_jSearchCategoryActionPerformed

    private void m_jPriceBuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jPriceBuyActionPerformed
        String inputText=m_jPriceBuy.getText();
        if(!inputText.isEmpty()&&inputText.startsWith("*")&&inputText.length()>1){
             inputText=inputText.substring(1);
             Double dPriceBuy = readCurrency(inputText);
             int quantity;
            try {
                quantity = (Integer) Formats.INT.parseValue(jm_quantity.getText());
            } catch (BasicException ex) {
                quantity=1;
            }
            m_jPriceBuy.setText(Formats.CURRENCY.formatValue(dPriceBuy/quantity));
        }
    }//GEN-LAST:event_m_jPriceBuyActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jCustomerPriceLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField jMnemonic;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jSearchCategory;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField jm_origin;
    private javax.swing.JTextField jm_quantity;
    private javax.swing.JTextField jm_sManufacturer;
    private javax.swing.JTextField jm_similarCode;
    private javax.swing.JTextField jm_unit;
    private javax.swing.JComboBox m_jAtt;
    private javax.swing.JTextField m_jCatalogOrder;
    private javax.swing.JComboBox m_jCategory;
    private javax.swing.JTextField m_jCode;
    private javax.swing.JComboBox m_jCodetype;
    private javax.swing.JCheckBox m_jComment;
    private javax.swing.JTextField m_jCustomerPrice;
    private javax.swing.JTextField m_jCustomerPriceMargin;
    private com.openbravo.data.gui.JImageEditor m_jImage;
    private javax.swing.JCheckBox m_jInCatalog;
    private javax.swing.JTextField m_jName;
    private javax.swing.JTextField m_jPriceBuy;
    private javax.swing.JTextField m_jPriceSell;
    private javax.swing.JTextField m_jPriceSellTax;
    private javax.swing.JTextField m_jRef;
    private javax.swing.JCheckBox m_jScale;
    private javax.swing.JComboBox m_jTax;
    private javax.swing.JLabel m_jTitle;
    private javax.swing.JTextField m_jmargin;
    private javax.swing.JTextField m_jstockcost;
    private javax.swing.JTextField m_jstockvolume;
    JButton JProductReserveBtn;

    
    protected I_ParentNode<String> parentNode;
    protected int parentState;
    private JTextField m_jWholesalePrice;
    private JTextField m_jWholesalePriceMargin;
    private JTextField textField_2;
    private JTextField jCurDate;
    private JTextField jWeight;
    private JTextField jSpecification;
	private JButton m_jButtonDaBao;

	@Override
	public void parentNodeValueChange(int state, I_ParentNode<String> parent) {
		 this.parentState=state;
	     this.parentNode=parent;
	}

	@Override
	public String getTabName() {
		return AppLocal.getIntString("Menu.Products");
	}

	@Override
	public void hostSelected(ProductExt product) {
	        if(state==STATE_Insert){
	        	m_jName.setText(Formats.STRING.formatValue(product.getName()));
	        	jm_quantity.setText(Formats.DOUBLE.formatValue(product.getM_quantity()));
	        	jm_sManufacturer.setText(Formats.STRING.formatValue(product.getM_sManufacturer()));
	        	jm_origin.setText(Formats.STRING.formatValue(product.getM_origin()));
		        jm_unit.setText(Formats.STRING.formatValue(product.getM_unit()));
	        	jm_iDurability.setText(Formats.INT.formatValue(product.getM_iDurability()));
	        	m_CategoryModel.setSelectedKey(product.getCategoryID());
	            taxcatmodel.setSelectedKey(product.getTaxCategoryID()); 
	            m_jPriceBuy.setText(Formats.CURRENCY.formatValue(product.getPriceBuy()));
	            m_jPriceSell.setText(Formats.CURRENCY.formatValue(product.getPriceSell())); 
	            dirty.setDirty(true);
	        }
	}

	@Override
	public String validator(ProductExt obj) {
		if(state==STATE_Insert){
			List<Product> products=null;
			try {
				products=ProductUtil.getProductInfo(dlSales, obj.getCode());	
			} catch (BasicException e) {
				return e.getMessage();
			}
			if(!products.isEmpty()){
				String message="已有如下同码商品：\n";
				for(Product p:products)
					message+=p.getName()+":"+p.getPriceSell()+"\n";
				 int res = JOptionPane.showConfirmDialog(this, message+"\n是否新增", AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			        if (res == JOptionPane.NO_OPTION)
			        	return AppLocal.getIntString("message.prodExist");
			}
		}
		return super.validator(obj);
	}
	
	
	
	public void configTotalPanel(JPanel extPanel) {
		m_jButtonDaBao=new JButton();
		//m_jButtonDaBao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
		m_jButtonDaBao.setText("包");
		m_jButtonDaBao.setFocusPainted(false);
	    m_jButtonDaBao.setFocusable(false);
	    m_jButtonDaBao.setMargin(new java.awt.Insets(8, 16, 8, 16));
	    m_jButtonDaBao.setRequestFocusEnabled(false);
	    m_jButtonDaBao.addActionListener(new java.awt.event.ActionListener() {
	        public void actionPerformed(java.awt.event.ActionEvent evt) {
	            m_jButtonDaBaoActionPerformed(evt);
	        }
	    });
	    extPanel.add(m_jButtonDaBao);
		
	}

	protected void m_jButtonDaBaoActionPerformed(ActionEvent evt) {
		ProductsEditor bomEditor=new ProductsEditor(this.dlSales,new DirtyManager());
		JEditorWarpDialog<ProductExt> bomDialog=JEditorWarpDialog.getInstance(this).init(dlSales,bomEditor);
		
		ProductExt newObj=new ProductExt();
		newObj.setCategoryID(obj.getCategoryID());
		newObj.setTaxCategoryID(obj.getTaxCategoryID());
		newObj.setM_sManufacturer(obj.getM_sManufacturer());
		newObj.setM_origin(obj.getM_origin());
		String bName=obj.getM_quantity()==1.0?obj.getName():obj.getM_quantity()+(obj.getM_unit()==null?"":obj.getM_unit())+obj.getName();
		newObj.setName(bName);
		newObj.setPriceBuy(obj.getM_quantity()*obj.getPriceBuy());
		newObj.setPriceSell(obj.getM_quantity()*obj.getPriceSell());
		
		try {
			bomDialog.activate();
			bomDialog.writeValueInsert(newObj);	
		} catch (BasicException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ProductExt retObj=bomDialog.getRetObj();
        if(retObj!=null){
        	ProductBom newBom=new ProductBom(retObj.getID());
        	newBom.setProductID(obj.getID());
        	newBom.setUnits(obj.getM_quantity());
        	try {
				dlSales.insert(newBom);
			} catch (BasicException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		
		
	}
	
	
}
